package com.tbit.uqbike.push.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.push.constant.GatewayProtocol;
import com.tbit.uqbike.push.pojo.OrderLog;
import com.tbit.uqbike.push.pojo.TerPosition;
import com.tbit.uqbike.push.service.MachineStatusService;
import com.tbit.uqbike.push.service.OrderLogService;
import com.tbit.uqbike.push.service.TerControlService;
import com.tbit.uqbike.push.util.DateTimeUtil;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("queueListenter")
public class QueueListenter {
    private final static Logger log = Logger.getLogger(QueueListenter.class);
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private TerControlService terControlService;
    @Autowired
    private OrderLogService orderLogService;

    @RabbitListener(queues = {"${mq.queue.ter_position_push}"}, concurrency = "10")
    @RabbitHandler
    public void onMessage(Message msg) {
        try {
            String respMsg = new String(msg.getBody(), "UTF-8");
            /**判断消息类型*/
            JSONObject object = JSON.parseObject(respMsg);
            int msgId = object.getIntValue("msgId");
            switch (msgId) {
                case GatewayProtocol.MQ_MSG_ID_POS_PUSH: //位置推送
                    TerPosition terPosition = JSON.parseObject(object.getString("data"), TerPosition.class);
                    machineStatusService.updatePosition(terPosition);
                    break;
                case GatewayProtocol.MQ_MSG_ID_CONTROL_TER_RSP://终端回复
                    log.info(respMsg);

                    String serNO = object.getJSONObject("data").getString("serNO");
                    String controlRet = object.getJSONObject("data").getString("controlRet");

                    terControlService.respHandle(serNO, controlRet);

                    /**更新远程控制日志*/
                    OrderLog orderLog = new OrderLog();
                    orderLog.setOrderSerNo(serNO);
                    orderLog.setRspDt(DateTimeUtil.getNowTime());
                    orderLog.setRspRet(Integer.parseInt(controlRet));
                    orderLog.setRspContent(controlRet);

                    orderLogService.update(orderLog);
                    break;
                default:
                    log.warn("未知消息类型=" + msgId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
